import { createStore } from "vuex";
import { getLoggedUser, clearLogged, setLoggedUser } from "../utils/stateUtils";

const CURRENT_MENU = "currentMenu";

// 创建一个新的 store 实例
const store = createStore({
  state() {
    return {
      loggedUser: null,
      currentMenu: "/admin/dashboard",
    };
  },
  getters: {
    loggedUser(state) {
      // 咱也不知道为什么, 反正这么用才能 不刷新完成 退出登录 功能
      state.loggedUser = getLoggedUser();
      return state.loggedUser;
    },
    currentMenu(state) {
      // 优先使用 sessionStorage 里的数据
      return sessionStorage.getItem(CURRENT_MENU) || state.currentMenu;
    },
  },
  mutations: {
    setLoggedUser(state, user) {
      setLoggedUser(user);
      state.loggedUser = user;
    },
    clearLogged(state) {
      clearLogged();
      state.loggedUser = null;
      state.currentMenu = null;
    },
    setAvatar(state, avatar) {
      state.loggedUser.avatar = avatar;
      setLoggedUser(state.loggedUser);
    },
    setCurrentMenu(state, menu) {
      state.currentMenu = menu;
      sessionStorage.currentMenu = menu;
    },
  },
});

export { store };
